package club.pchome.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import club.pchome.annotation.NoAuth;
import club.pchome.common.constant.SystemConstant;
import club.pchome.common.util.JwtUtils;
import club.pchome.dto.Result;
import club.pchome.ex.ServiceException;
import club.pchome.model.UserAdmin;
import club.pchome.service.UserAdminService;
import club.pchome.util.MD5Util;
import club.pchome.util.TUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
public class LoginController extends BaseController{

	@Autowired
	UserAdminService userAdminService;

	@Autowired
	JwtUtils jwtUtils;


	@NoAuth
	@ApiOperation(value = "登录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "username", value = "账号(手机号)", required = true), @ApiImplicitParam(name = "password", value = "密码", required = true) })
	@PostMapping("/login")
	public Result<Map<String, String>> login(String username, String password) throws Exception {
		TUtil.checkObj(new String[] { "账号为空", "密码为空" }, username, password);

		UserAdmin login = userAdminService.login(username, MD5Util.md5(password));
		
		if (null == login) {
			throw new ServiceException(SystemConstant.RESCODE_LOGIN , "账号或密码错误");
		}

		//把token返回给客户端-->客户端保存至cookie-->客户端每次请求附带cookie参数
		String JWT = jwtUtils.createJWT("1", username, SystemConstant.JWT_TTL);
		paramMap.put("phone", login.getPhone());
		paramMap.put("holder", login.getHolder());
		paramMap.put("token", JWT);

		return Result.initSuccessResult(paramMap);
	}
}
